package com.gec.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gec.entity.Member;
import com.gec.service.MemberService;
import com.gec.service.impl.MemberServiceimpl;
@WebServlet("/melogin")
public class MemberLoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//将请求转发到login.jsp页面
		req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String code = req.getParameter("code");
		if(!code.equalsIgnoreCase((String)req.getSession().getAttribute("stand"))) {
			req.setAttribute("err", "验证码不符合");
			req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
			return;
		}
		//获取login.jsp上输入的账号和密码
		String name = req.getParameter("name");
		String pwd = req.getParameter("inputPassword");
		
		//通过service.login(name,pwd);方法查询数据库中是否有前台输入的账号和密码，并将查询结果传给me
		MemberService service = new MemberServiceimpl();
		Member me = service.login(name,pwd);
		
		//判断me是否为空,
		if(me != null) {   
			//如果不为空则是数据库中有该账号密码 
			req.getSession().setAttribute("member", me);//me值不为空时,则将me值存入session中,在过滤器中进行过滤(没有登录就不能访问其他页面)。"member"与过滤器中"member"相对应
			resp.sendRedirect(req.getContextPath()+"/melist");
		}else {
			//如果为空则是数据库中没有该账号或密码 ,则转发回login.jsp页面
			req.setAttribute("err", "用户名或密码不符");
			req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
		}
	}
	
}
